package com.dhh.sky.activity;

import java.text.DecimalFormat;
import org.json.JSONObject;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.actionbarsherlock.view.MenuItem;
import com.devspark.appmsg.AppMsg;
import com.dhh.sky.R;
import com.dhh.sky.SDAApplication;
import com.dhh.sky.util.CUtil;
import com.dhh.sky.util.Constant;
import com.dhh.sky.widget.SlideMenuFragment;
import com.microsoft.live.LiveAuthException;
import com.microsoft.live.LiveAuthListener;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveConnectSession;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveStatus;
import com.slidingmenu.lib.SlidingMenu;
import com.slidingmenu.lib.app.SlidingFragmentActivity;

public class SettingActivity extends SlidingFragmentActivity {
	private TextView spaceNum;
	private TextView accountView;
	private ProgressBar progressBar;
	private Button btLogout;
	private LiveConnectClient client;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setBehindContentView(R.layout.menu_frame);
		setContentView(R.layout.setting);

		client = ((SDAApplication) getApplication()).getConnectClient();
		
		getSupportFragmentManager().beginTransaction().replace(R.id.menu_frame, new SlideMenuFragment()).commit();
		SlidingMenu sm = getSlidingMenu();
		sm.setShadowWidthRes(R.dimen.shadow_width);
		sm.setShadowDrawable(R.drawable.shadow);
		sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		sm.setFadeDegree(0.35f);
		sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);

		initActionBar();
		initView();
		
		updateSetting();
	}
	
	private void initView(){
		spaceNum = (TextView) this.findViewById(R.id.st_space_num);
		progressBar = (ProgressBar) this.findViewById(R.id.st_percent);
		accountView = (TextView) this.findViewById(R.id.st_account);
		btLogout = (Button) this.findViewById(R.id.st_logout);
		btLogout.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				setSupportProgressBarIndeterminateVisibility(true);
                ((SDAApplication) getApplication()).getAuthClient().logout(new LiveAuthListener(){
                    @Override
                    public void onAuthError(LiveAuthException exception, Object userState){
                        setSupportProgressBarIndeterminateVisibility(false);
                        startActivity(new Intent(getApplicationContext(), SDAActivity.class));
                        finish();
                        removeToken();
                        Log.e(Constant.TAG, "Error: " + exception.getMessage());
                    }

					@Override
					public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
						setSupportProgressBarIndeterminateVisibility(false);
                        startActivity(new Intent(getApplicationContext(), SDAActivity.class));
                        finish();
                        removeToken();						
					}
                });				
			}
		});
	}
	
	private void removeToken(){
		SharedPreferences sp = getSharedPreferences("com.microsoft.live", Context.MODE_PRIVATE);		
		sp.edit().remove("refresh_token").commit();
		sp.edit().remove("cookies").commit();
	}
	
	private void updateSetting(){
		if(CUtil.isNetworkAvailable(this)){
			new RefreshTask().execute();
		}else{
			accountView.setText(getString(R.string.label_unknow));
			spaceNum.setText(getString(R.string.label_unknow));
			CUtil.showToast(this, R.string.msg_error_network, AppMsg.STYLE_ALERT);
		}
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			toggle();
			return true;
		}

		return false;
	}

	private void initActionBar() {
		getSupportActionBar().setHomeButtonEnabled(true);
		getSupportActionBar().setIcon(R.drawable.ic_app_menu);
		getSupportActionBar().setDisplayHomeAsUpEnabled(false);
		getSupportActionBar().setTitle(this.getString(R.string.title_setting));
	}
	
	public class GetQuotaTask extends AsyncTask<Void, Void, Void>{
		@Override
		protected Void doInBackground(Void... params) {
			return null;
		}
		
	}
	
	class RefreshTask  extends AsyncTask<Void, Void, Void> {
		long total = 0;
		long available = 0;
		
		@Override
		protected Void doInBackground(Void... params) {
			progressHandler.sendEmptyMessage(0);
			try {
				Message msg = CUtil.buildMessage();
				msg.getData().putBoolean(Constant.PARAM_DONE, true);
				
				LiveOperation op = client.get("me");
				JSONObject emails = op.getResult().optJSONObject("emails");
				msg.getData().putString("account", emails.getString("account"));
				
				LiveOperation operation = client.get("me/skydrive/quota");
				total = operation.getResult().getLong("quota");
				available = operation.getResult().getInt("available");
				
				
				msg.getData().putLong("total", total);
				msg.getData().putLong("available", available);
				refreshHandler.sendMessage(msg);
				
				
				
			} catch (Exception e) {
				Log.e(Constant.TAG, e.getMessage(),e);
				Message msg = CUtil.buildMessage();
				msg.getData().putBoolean(Constant.PARAM_DONE, false);
				refreshHandler.sendMessage(msg);
			}
			progressHandler.sendEmptyMessage(1);
			return null;
		}
		
	}
	
	private Handler refreshHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {    
        	if(msg.getData().getBoolean(Constant.PARAM_DONE)){
        		long total = msg.getData().getLong("total");
        		long available = msg.getData().getLong("available");
        		accountView.setText(msg.getData().getString("account"));
        		spaceNum.setText(formatByteSize(total-available)+" / "+formatByteSize(total));
				progressBar.setMax(Long.valueOf(convertBytes2Gb(total)).intValue());
				progressBar.setProgress(Long.valueOf(convertBytes2Gb(total-available)).intValue());
				progressBar.setVisibility(View.VISIBLE);
        	}else{
        		spaceNum.setText("Unknow");
        		accountView.setText("Unknow");
        	}
        }
    };
    
    private Handler progressHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {    
        	if(msg.what==0){
            	setSupportProgressBarIndeterminateVisibility(true);
        	}else{
            	setSupportProgressBarIndeterminateVisibility(false);
        	}
        }
    };
    
    private long convertBytes2Gb(long value){
    	return value / 1024 / 1024 / 1024;
    }
    
    public static String formatByteSize(long size) {
        if(size <= 0) return "0";
        final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
        int digitGroups = (int) (Math.log10(size)/Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size/Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }

	
}
